<?php
/**
 * Created by PhpStorm.
 * User: 柳迪
 * Date: 2018/7/11
 * Time: 8:07
 */

namespace app\api\controller;


use think\Controller;
use think\Session;

class common extends Controller
{
    public function login()
    {
        if(input('?password') && input('?username'))
        {
            $password=input('password');
            $username=input('username');
            $result=db('users')->field('uid')->where('uname',$username)->where('upassword',$password)->find();
            if($result)
            {
                Session::set('uid',$result['uid']);
                echo json_encode(['uid'=>$result['uid']]);
            }
            else
                echo json_encode(['uid'=>0]);
        }
        else
            echo json_encode(['uid'=>0]);
        die();
    }


    public function register()
    {
        if(input('?username') && input('?password'))
        {
            $data['uname']=input('username');
            $result_confirm=db('users')->where('uname',input('username'))->find();
            if($result_confirm)
            {
                echo json_encode(['status'=>0,'message'=>'用户名已被使用，请重试。']);
                die();
            }
            $data['upassword']=input('password');
            if(input('?tel'))
            {
                $tel=input('tel');
                $isMob="/^1[3-8]{1}[0-9]{9}$/";
                $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
                if(!preg_match($isMob,$tel) && !preg_match($isTel,$tel))
                {
                    echo json_encode(['status'=>0,'message'=>'电话格式错误，请重试。']);
                    die();
                }
                else
                {
                    $data['utel']=$tel;
                }
            }
            if(input('?email'))
            {
                $email=input('email');
                $pattern="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
                if(preg_match($pattern,$email))
                {
                    $data['uemail']=$email;
                }
                else
                {
                    echo json_encode(['status'=>0,'message'=>'邮箱格式错误，请重试。']);
                    die();
                }
            }
            $result=db('users')->insert($data);
            if($result)
            {
                echo json_encode(['status'=>1,'message'=>'注册成功。']);
                die();
            }
            else
            {
                echo json_encode(['status'=>0,'message'=>'注册失败，错误未知。']);
                die();
            }
        }
        else
        {
            echo json_encode(['status'=>0,'message'=>'参数错误']);
        }
    }

}